package com.snk.back.service.impl;



import com.snk.back.dao.SysMenuDao;
import com.snk.back.dao.SysRoleMenuDao;
import com.snk.back.dao.SysUserRoleDao;
import com.snk.back.service.SysMenuService;
import com.snk.common.annotation.RequiredLog;
import com.snk.common.pojo.Node;
import com.snk.common.utils.AssertUtils;
import com.snk.pojo.SysMenu;
import com.snk.pojo.SysUserMenu;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    @RequiresPermissions("sys:menu:view")
    @Override
    public List<SysMenu> findObjects() {
        List<SysMenu> list=sysMenuDao.findObjects();

        AssertUtils.isServiceValid(list==null || list.size()==0,"没有对应的菜单");
        return list;

    }
    @RequiresPermissions("sys:menu:delete")
    @Override
    public int deleteObject(Integer id) {

        AssertUtils.isValid(id==null||id<=0, "请先选择");
        int count=sysMenuDao.getChildCount(id);
        AssertUtils.isValid(count>0, "请先删除子菜单");
        //删除角色菜单关系数据
        sysRoleMenuDao.deleteObjectsByMenuId(id);
        int rows=sysMenuDao.deleteObject(id);

        AssertUtils.isServiceValid(rows==0, "此菜单可能已经不存在");
        return rows;
    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        return sysMenuDao.findZtreeMenuNodes();
    }

    @RequiresPermissions("sys:menu:add")
    @Override
    public int insertObject(SysMenu sysMenu) {

        AssertUtils.isValid(sysMenu==null, "保存对象不能为空");
        AssertUtils.isValid(StringUtils.isEmpty(sysMenu.getName()),"菜单名不能为空");
        int rows=sysMenuDao.insertObject(sysMenu);

        return rows;
    }

    @RequiresPermissions("sys:menu:update")
    @Override
    public int updateObject(SysMenu sysMenu) {


        AssertUtils.isValid(sysMenu==null, "保存对象不能为空");
        AssertUtils.isValid(StringUtils.isEmpty(sysMenu.getName()),"菜单名不能为空");
        int rows=sysMenuDao.updateObject(sysMenu);

        AssertUtils.isServiceValid(rows==0, "记录可能已经不存在");
        return rows;
    }
    @RequiredLog
    @Override
    public List<SysUserMenu> findUserMenusByUserId(Integer id) {
        //对用户id进行判定
        AssertUtils.isValid(id==null||id<0, "id置无效");
        List<Integer> roleIds=
                sysUserRoleDao.findRoleIdsByUserId(id);
        List<Integer> menuIds=
                sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);

        return sysMenuDao.findMenusByIds(menuIds);
    }
}
